import requests
from bs4 import BeautifulSoup
import csv

# 设置请求头，模拟浏览器访问
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}

# 获取所有汽车品牌列表
def get_brands():
    url = "https://car.autohome.com.cn/grade/carhtml/index.html"
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    soup = BeautifulSoup(response.text, 'html.parser')
    
    brands = {}
    for script in soup.find_all('script'):
        if 'var carData' in script.text:
            script_text = script.text
            start_index = script_text.find('var carData = ') + len('var carData = ')
            end_index = script_text.find('};', start_index) + 1
            car_data = script_text[start_index:end_index]
            car_data = car_data.replace('var carData = ', '').replace('};', '}')
            brands = eval(car_data)
            break
    
    return brands

# 获取每个品牌的子型号列表
def get_models(brand_url):
    response = requests.get(brand_url, headers=headers)
    response.raise_for_status()
    soup = BeautifulSoup(response.text, 'html.parser')
    
    models = []
    for dl in soup.find_all('dl', class_='models-list'):
        for dt in dl.find_all('dt'):
            model_name = dt.find('a').get_text(strip=True)
            models.append(model_name)
    
    return models

# 主函数
def main():
    brands = get_brands()
    all_data = []

    for letter, brand_list in brands.items():
        for brand in brand_list:
            brand_name = brand['name']
            brand_url = f"https://car.autohome.com.cn{brand['url']}"
            models = get_models(brand_url)
            for model in models:
                all_data.append([brand_name, model])
    
    # 保存到CSV文件
    with open('autohome_brands_and_models.csv', 'w', newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['Brand', 'Model'])
        writer.writerows(all_data)
    
    print("数据已成功保存到 autohome_brands_and_models.csv 文件中")

if __name__ == "__main__":
    main()